package tcp;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket clientSocket;
    private String serverIp;
    private int serverPort;

    public TcpEchoClient( String serverIp, int serverPort) throws IOException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        this.clientSocket = new Socket(serverIp,serverPort);
    }

    public void start(){
        System.out.println("客户端启动 ");
        Scanner scanner = new Scanner(System.in);
        try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()))){
            while(true){
                System.out.print("->");
                String request = scanner.next();
                if("exit".equals(request)) break;
                bufferedWriter.write(request+"\n");
                bufferedWriter.flush();
                String response = bufferedReader.readLine();
                System.out.println(response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("8.142.191.35",9191);
        tcpEchoClient.start();
    }
}
